<?php

namespace app\admin\controller\science;

use think\response\Json;
use think\response\View;
use app\admin\controller\Controller;

class Feedback extends Controller
{
    /**
     * @var \app\admin\service\science\FeedbackService
     */
    protected $service = null;
    /**
     * 重写中间件配置
     */
     protected array $middleware = ['operLog'];
    public function initialize()
    {
        parent::initialize();
        $this->service = new \app\admin\service\science\FeedbackService();
    }

    /**
     * 反馈列表
     * @return Json
     * @throws \think\db\exception\DbException
     */
    public function list(): Json
    {
        return success($this->service->list());
    }

    /**
     * 反馈详情
     * @param int $id
     * @return Json
     */
    public function detail(int $id): Json
    {
        return success($this->service->detail($id));
    }

    /**
     * 处理反馈
     * @param int $id
     * @return Json
     */
    public function process(int $id): Json
    {
        return success('处理成功', $this->service->process($id, request()));
    }

    /**
     * 删除反馈
     * @return Json
     */
    public function delete(): Json
    {
        return success($this->service->delete());
    }

    /**
     * 创建/编辑反馈表单页面
     * @param int|null $id
     * @return View
     */
    public function create(int $id = null): View
    {
        $data = [];
        if ($id) {
            $detail = $this->service->detail($id);
            if ($detail) {
                $data = $detail->toArray();
            }
        }
        $viewData = [
            'id' => $id
        ];
        return view('science/feedback/create', $viewData);
    }

    /**
     * 保存反馈表单数据
     * @param int|null $id
     * @return Json
     */
    public function save(int $id = null): Json
    {
        try {
            $result = $this->service->process($id, $this->request);
            if ($result) {
                return success('保存成功');
            } else {
                return error('保存失败');
            }
        } catch (\Exception $e) {
            return error($e->getMessage());
        }
    }
}